package com.svms.save.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.svms.save.cache.LicenseCache;
import com.svms.save.services.LicenseService;
import com.svms.save.vo.LicenseVo;
import com.svms.save.vo.ResultVo;

@Controller
@RequestMapping("/license")
public class LicenseController {
	
	Logger log = LoggerFactory.getLogger(LicenseController.class);
	@Autowired
	private LicenseService licenseManager;
	
	@RequestMapping("/page")
	public String toLicense() {
		return "license/page";
	}
	@RequestMapping("/thisLicense")
	@ResponseBody
	public ResultVo<LicenseVo> thisLicense(){
		ResultVo<LicenseVo> res = null;
		try {
			LicenseVo licen = licenseManager.validateLicense(true);
			res = ResultVo.success("", licen);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("系统错误！",e);
			LicenseVo licen = new LicenseVo();
			licen.setState(ResultVo.SYSTEM_ERROR);
			licen.setErrMsg(LicenseService.ERRMSG_LICENSE_FILE);
			res = ResultVo.systemError("系统错误！",licen);
		}
		return res;
	}
	@RequestMapping("/thisLicenseKey")
	@ResponseBody
	public ResultVo<String> thisLicenseKey(){
		ResultVo<String> res = null;
		try {
			String licen = licenseManager.getLicenseKey();
			res = ResultVo.success("", licen);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("系统错误！",e);
			res = ResultVo.systemError("系统错误！","服务器网卡异常！");
		}
		return res;
	}
	@RequestMapping("/doSaveLicense")
	@ResponseBody
	public ResultVo<LicenseVo> doWriteLicense(String licenseCode){
		ResultVo<LicenseVo> res = null;
		try {
			LicenseVo license = licenseManager.writeLicense(licenseCode);
			LicenseCache.replaceLicense(license);
			res = ResultVo.success("", license);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("系统错误！",e);
			LicenseVo licen = new LicenseVo();
			licen.setState(ResultVo.SYSTEM_ERROR);
			licen.setErrMsg(LicenseService.ERRMSG_LICENSE_FILE);
			res = ResultVo.systemError("系统错误！",licen);
		}
		return res;
	}
}
